package com.project.springboot.repository;

import com.project.springboot.dataobject.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description：商品DAO
 * Created by 朱正磊 on 2019/3/12 0012 下午 5:32
 */
public interface ProductRepository extends JpaRepository<Product, Integer> {

    //单表简单查询
    List<Product> findByUsername(String username);

    List<Product> findProductsByUsernameAndEmail(String username, String email);

    List<Product> findProductsByPname(String pname);

    List<Product> findFirst2ByPname(String pname);

    List<Product> findTop4ByPnameIsNotNull();

    //分页查询
    Page<Product> findByUsername(String username, Pageable pageable);

    //自定义sql语句
    @Query(value = "select p from Product p where p.pid = ?1")
    Product findByPid(Integer pid);

    @Query(value = "select p from Product p where p.pname = ?1")
    List<Product> queryByPname(String pname);

    @Transactional
    @Modifying
    @Query(value = "update Product p set p.pname = ?1 where p.pid = ?2")
    Integer updateProduct(String pname, Integer pid);

    @Transactional
    @Modifying
    @Query(value = "delete from Product p where p.pid = ?1")
    Integer deleteProduct(Integer pid);

    @Transactional
    @Modifying
    @Query(value = "insert into product (pname, username, email) values (:pname, :username, :email)", nativeQuery = true)
    Integer addProduct(@Param("pname") String pname, @Param("username") String username, @Param("email") String email);
}
